package com.example.myapplication;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;


public class ControlActivity extends Activity implements OnClickListener {
    private TargetMsg targetMsg;
    private int _isReady;
    private Boolean _isAuto = false;
    private int _yaw;
    private int _pitch;
    private int _distance;
    private TextView _tv_ready;
    private TextView _tv_yaw;
    private TextView _tv_pitch;
    private TextView _tv_distance;
    private SeekBar _sb_yaw;
    private SeekBar _sb_pitch;
    private SeekBar _sb_distance;
    private Button _bt_yaw;
    private Button _bt_pitch;
    private Button _bt_distance;
    private EditText _et_yaw;
    private EditText _et_pitch;
    private EditText _et_distance;
    private Button _bt_launch;
    private Button _bt_retrieve;
    private final Handler handler = new Handler();

    @SuppressLint({"DefaultLocale", "SetTextI18n", "ResourceType", "UseSwitchCompatOrMaterialCode"})
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.control);

        this.targetMsg = new TargetMsg();
        _tv_ready = findViewById(R.id.tv_ready);

        _tv_yaw = findViewById(R.id.tv_yaw);
        _tv_pitch = findViewById(R.id.tv_pitch);
        _tv_distance = findViewById(R.id.tv_distance);
        _sb_yaw = findViewById(R.id.sb_yaw);
        _sb_pitch = findViewById(R.id.sb_pitch);
        _sb_distance = findViewById(R.id.sb_distance);
        _bt_yaw = findViewById(R.id.bt_yaw);
        _bt_pitch = findViewById(R.id.bt_pitch);
        _bt_distance = findViewById(R.id.bt_distance);
        _et_yaw = findViewById(R.id.et_yaw);
        _et_pitch = findViewById(R.id.et_pitch);
        _et_distance = findViewById(R.id.et_distance);

        _bt_launch = findViewById(R.id.bt_launch);
        _bt_retrieve = findViewById(R.id.bt_retrieve);



        // State switch 控件
        Switch stateSwitch = findViewById(R.id.sw_state);
        stateSwitch.setOnCheckedChangeListener(new setState(stateSwitch));
        // TODO: random
//        Switch randomSwitch = findViewById(R.id.sw_random);
//        randomSwitch.setOnCheckedChangeListener(new setRandom(randomSwitch));

        // yaw 角度控件
        setTarget setYaw = new setTarget(_sb_yaw, _et_yaw, _bt_yaw, "yaw");
        // pitch 角度控件
        setTarget setPitch = new setTarget(_sb_pitch, _et_pitch, _bt_pitch, "pitch");
        // dis 发射距离控件
        setTarget setDistance = new setTarget(_sb_distance, _et_distance, _bt_distance, "distance");
        // launch 按钮
        _bt_launch.setOnClickListener(v -> {
            targetMsg.setLaunch(true);
            changeTarget();
            targetMsg.setLaunch(false);
        });
        // Retrieve 按钮
        _bt_retrieve.setOnClickListener(v -> {
            targetMsg.setRetrieve(true);
            changeTarget();
            targetMsg.setRetrieve(false);
        });

        //创建断开连接的按钮
        Button bt_dis = (Button) findViewById(R.id.bt_disconnect);
        bt_dis.setOnClickListener(this);
        bt_dis.setTextColor(0xFF6200EE);

        handler.postDelayed(task, 500); // TODO
    }

    private void refreshPage() {
        if(!_isAuto){
            if(_isReady == 0){
                _tv_ready.setText("发球机还未准备就绪，请勿操作");
                setEnable(false, false);
            } else if (_isReady == 1) {
                _tv_ready.setText("发球机已准备好发球/更改状态");
                setEnable(true,false);
            }
        }

        _tv_yaw.setText(String.valueOf(_yaw));
        _tv_pitch.setText(String.valueOf(_pitch));
        _tv_distance.setText(String.valueOf(_distance));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        TCPClient.getInstance().close();
        handler.removeCallbacks(task);
    }

    private final Runnable task = new Runnable() {
        @Override
        public void run() {
            if(stateRefresh()==false){
                Toast toast = Toast.makeText(getApplicationContext(), "获取状态失败，请检查服务端，8秒后重试", Toast.LENGTH_SHORT);
                showMyToast(toast, 1500);
                handler.postDelayed(this, 8000);
            }else {
                handler.postDelayed(this, 1000);
            }
        }
    };

    public boolean stateRefresh() {
        RefreshCallable rInitial = new RefreshCallable();
        FutureTask<byte[]> futureTask = new FutureTask<>(rInitial);
        Thread thread = new Thread(futureTask, "通信子线程");
        System.out.println("=========更新数据===========");
        thread.start();
        try {
            byte[] stateMsg = futureTask.get();
            // TODO 确定返回的消息长度
            if (stateMsg.length != 4) {
                Log.d("ControlActivity", "state msg refresh fail: ");
                return false;
            }
            this._isReady = stateMsg[0];
            this._yaw = stateMsg[1];
            this._pitch = stateMsg[2];
            this._distance = stateMsg[3];
        } catch (ExecutionException | InterruptedException e) {
            e.printStackTrace();
            return false;
        }
        refreshPage();
        return true;
    }

    @Override
    public void onClick(View view) {
        //断开连接，跳转到登录界面
        Intent intent = new Intent();
        intent.setClass(getApplicationContext(), MainActivity.class);
        startActivity(intent);
        TCPClient.getInstance().close();
        handler.removeCallbacks(task);
    }

    class setTarget {
        private final SeekBar seekBar;
        private final EditText editText;
        private final Button button;
        private final String handle;

        private setTarget(SeekBar seekBar, EditText editText, Button button, String handle) {
            this.seekBar = seekBar;
            this.editText = editText;
            this.button = button;
            this.handle = handle;
            if (handle == "distance"){
                this.seekBar.setProgress(8);
                this.editText.setText("8");
            }else{
                this.seekBar.setProgress(0);
                this.editText.setText("0");
            }

            this.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    // 滑动条进度发生变化时的回调
                    editText.setText(String.valueOf(progress));
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {
                    // 按住滑动条开始滑动时的回调
                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                    // 松开滑动条停止滑动时的回调
                }
            });

            this.editText.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    // 文本改变之前的回调
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    // 文本改变时的回调
                    try {
                        int value = Integer.parseInt(s.toString());
                        seekBar.setProgress(value);
                    } catch (NumberFormatException e) {
                        // 如果输入的文本无法解析为整数，可以在此处进行错误处理
                    }
                }

                @Override
                public void afterTextChanged(Editable s) {
                    // 文本改变之后的回调
                }
            });

            this.button.setOnClickListener(v -> {
                if (Utils.isFastClick()) {
                    Toast toast = Toast.makeText(getApplicationContext(), "点击速度太快，请重试", Toast.LENGTH_SHORT);
                    showMyToast(toast, 500);
                    return;
                }
                String text = editText.getText().toString();
                if (text.isEmpty()) {
                    Toast toast = Toast.makeText(getApplicationContext(), "文本框内没有数值", Toast.LENGTH_SHORT);
                    showMyToast(toast, 500);
                    return;
                }
                int value = Integer.parseInt(text);
                switch (handle) {
                    case "yaw":
                        targetMsg.setYaw(value);
                        break;
                    case "pitch":
                        targetMsg.setPitch(value);
                        break;
                    case "distance":
                        targetMsg.setDistance(value);
                        break;
                    default:
                        System.out.println("没有这种handle");
                        break;
                }
                changeTarget();
            });
        }
    }

    @SuppressLint("UseSwitchCompatOrMaterialCode")
    class setState implements CompoundButton.OnCheckedChangeListener {
        private final Switch aSwitch;
        private final TextView textView;
        private final SeekBar sb_yaw;
        private final SeekBar sb_pitch;

        private setState(Switch aSwitch) {
            this.aSwitch = aSwitch;
            this.textView = findViewById(R.id.tv_state);
            this.sb_yaw = findViewById(R.id.sb_yaw);
            this.sb_pitch = findViewById(R.id.sb_pitch);
            this.textView.setText("手动");
        }

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (Utils.isFastClick()) {
                aSwitch.setChecked(!isChecked);
                Toast toast = Toast.makeText(getApplicationContext(), "点击速度太快，请重试", Toast.LENGTH_SHORT);
                showMyToast(toast, 500);
                return;
            }
            if (isChecked) {
                textView.setText("自动");
                targetMsg.setAuto(true);
                _isAuto = true;
                setEnable(false,true);
            } else {
                textView.setText("手动");
                targetMsg.setAuto(false);
                _isAuto = false;
                setEnable(true,true);
            }
            changeTarget();
        }
    }

    // TODO: random
/*
    @SuppressLint("UseSwitchCompatOrMaterialCode")
    class setRandom implements CompoundButton.OnCheckedChangeListener {
        private final Switch aSwitch;
        private final TextView textView;

        private setRandom(Switch aSwitch) {
            this.aSwitch = aSwitch;
            this.textView = findViewById(R.id.tv_random);
            this.textView.setText("否");
        }

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (Utils.isFastClick()) {
                aSwitch.setChecked(!isChecked);
                Toast toast = Toast.makeText(getApplicationContext(), "点击速度太快，请重试", Toast.LENGTH_SHORT);
                showMyToast(toast, 500);
                return;
            }
            if (isChecked) {
                textView.setText("是");
                targetMsg.setRandom(true);
            } else {
                textView.setText("否");
                targetMsg.setRandom(false);
            }
            changeTarget();
        }
    }*/

    public void changeTarget() {
        TargetCallable targetCallable = new TargetCallable();
        FutureTask<String> futureTask = new FutureTask<>(targetCallable);
        Thread thread = new Thread(futureTask, "通信子线程");
        thread.start(); //子线程执行
        try {
            System.out.println("改变目标：" + futureTask.get()); // TODO 获取返回结果是会阻塞
        } catch (ExecutionException | InterruptedException e) {
            e.printStackTrace();
        }
        Toast toast = Toast.makeText(getApplicationContext(), "目标值更新成功", Toast.LENGTH_SHORT);
        showMyToast(toast, 500);
    }

    static class RefreshCallable implements Callable<byte[]> {
        public byte[] call() throws Exception {
            TCPClient tcpClient = TCPClient.getInstance();
            if (tcpClient.isConnected()) {
                tcpClient.sendRefresh();
            }
            return tcpClient.getState();
        }
    }

    class TargetCallable implements Callable<String> {
        public String call() {
            TCPClient tcpClient = TCPClient.getInstance();
            if (tcpClient.isConnected()) {
                tcpClient.send(targetMsg);
            } else {
                Toast toast = Toast.makeText(getApplicationContext(), "TCP连接已断开，请检查连接", Toast.LENGTH_SHORT);
                showMyToast(toast, 500);
            }
            // TODO
//            return tcpClient.getData();
            return null;
        }
    }

    private void setEnable(Boolean flag, Boolean IncludeRetrieve) {
//            _sb_yaw.setEnabled(flag);
//            _sb_pitch.setEnabled(flag);
//            _sb_distance.setEnabled(flag);
            _bt_yaw.setEnabled(flag);
            _bt_pitch.setEnabled(flag);
            _bt_distance.setEnabled(flag);
//            _et_yaw.setEnabled(flag);
//            _et_pitch.setEnabled(flag);
//            _et_distance.setEnabled(flag);
            _bt_launch.setEnabled(flag);
            if(IncludeRetrieve){
                _bt_retrieve.setEnabled(flag); // TODO: 收球
            }
    }

    public static class Utils {
        // 两次点击按钮之间的点击间隔不能少于毫秒
        private static final int MIN_CLICK_DELAY_TIME = 1000; // TODO
        private static long lastClickTime;

        public static boolean isFastClick() {
            boolean flag = true;
            long curClickTime = System.currentTimeMillis();
            if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
                flag = false;
                lastClickTime = curClickTime;
            }
            return flag;
        }
    }

    public void showMyToast(final Toast toast, final int cnt) {
        final Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                toast.show();
            }
        }, 0, 3000);
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                toast.cancel();
                timer.cancel();
            }
        }, cnt);
    }
}

